package NetWork;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TcpThreadEchoServer {
    //    private ServerSocket listenSocket = null;
    private   ServerSocket serverSocket = null;

    public  TcpThreadEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动！");
        while (true){
            //由于tcp是有连接的，不是一上来就能读数据，需要先建立连接(打电话)
            //accept返回了一个socket对象
            Socket clinetSocket = serverSocket.accept();
            //在这个地方每次accept成功就创建一个新的线程，由新线程负责执行这个processConnection方法
            Thread t = new Thread(()->{
                processConnection(clinetSocket);
            });
            t.start();
        }
    }

    private void processConnection(Socket clinetSocket) {
        System.out.printf("[%s:%d客户端建立连接！\n",clinetSocket.getInetAddress().toString(),clinetSocket.getPort());
        //接下来处理请求与响应
        try(InputStream inputStream = clinetSocket.getInputStream()){
            try(OutputStream outputStream = clinetSocket.getOutputStream()){
                Scanner scanner = new Scanner(inputStream);//读取请求
                while (true){
                    //循环的处理每个请求 分别返回响应
                    if(!scanner.hasNext()){
                        System.out.printf("[%s:%d]客户端断开连接！\n",clinetSocket.getInetAddress().toString(),clinetSocket.getPort());
                        break;
                    }
                    String request = scanner.next();
                    //2、根据请求，断开响应！
                    String response = process(request);
                    //3、把这个响应返回给客户端
                    //为了方便起见，可以使用PrintWriter把OutputStream包裹一下
                    PrintWriter printWriter = new PrintWriter(outputStream);
                    printWriter.println(response);
                    //刷新缓冲区，如果没有这个刷新，可能客户端就不能第一时间看到响应结果。
                    printWriter.flush();
                    System.out.printf("[%s:%d] rep:%s,resp:%s\n",
                            clinetSocket.getInetAddress().toString(),clinetSocket.getPort(),request,response);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //记得关闭操作
            try {
                clinetSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpThreadEchoServer server = new TcpThreadEchoServer(9090);
        server.start();
        //注意先启动服务器 在启动客户端
    }
}

